package org.openclinic.controller;

import javax.servlet.http.HttpServletRequest;

import org.openclinic.domain.Attendant;
import org.openclinic.exception.AbstractExceptionHandler;
import org.openclinic.exception.DomainException;
import org.openclinic.exception.ErrorCodes;
import org.openclinic.service.AttendantService;
import org.openclinic.to.AjaxResponse;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.util.StringUtils;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestMethod;
import org.springframework.web.bind.annotation.RequestParam;
import org.springframework.web.bind.annotation.ResponseBody;

@Controller
public class AuthenticationController extends AbstractExceptionHandler {

	@Autowired
	private AttendantService userService;
	
	@ResponseBody
	@RequestMapping(value = "/auth.do", method = RequestMethod.POST)
	public AjaxResponse login(HttpServletRequest request, @RequestParam String username, @RequestParam String password) {
		Attendant user = null;
		
		if (!StringUtils.hasText(username) || !StringUtils.hasText(password)) {
			return new AjaxResponse("Ambos campos são obrigatórios");
		}

		user = userService.find(username, password);
		if (user == null) {
			return new AjaxResponse("Usuário ou senha inválido");
		}
		
		request.getSession().setAttribute("currentUser", user);
		
		return AjaxResponse.SUCCESS;
	}
	
	@RequestMapping(value = "/auth.do", method = RequestMethod.GET, params = "logout")
	public String logout(HttpServletRequest request) {
		request.getSession().invalidate();
		
		if (request.getHeader("Referer").indexOf("mobile") > -1) {
			return "redirect:/mobile";
		}
		return "redirect:/index.do";
	}
	
	@RequestMapping(value = "/password/open.diag", method = RequestMethod.POST)
	public String initNewForm() {	
		return ("change-password.jsp");
	}
	
	@ResponseBody		
	@RequestMapping(value = "/password/change.action", method = RequestMethod.POST)
	public AjaxResponse changePassword(@RequestParam String currentPassword, @RequestParam String newPassword) {	
		int rowsUpdated = userService.updatePassword(newPassword, currentPassword);
		
		if (rowsUpdated > 0) {
			return AjaxResponse.SUCCESS;
		}
		
		throw new DomainException("user", "currentPassword", ErrorCodes.INVALID_VALUE + ".currentPassword", currentPassword);
	}
}
